package com.lxt.controller;

import com.lxt.common.HttpResult;
import com.lxt.common.util.CookieUtils;
import com.lxt.common.util.JsonUtils;
import com.lxt.common.util.RedisOperator;
import com.lxt.enums.OrderStatusEnum;
import com.lxt.enums.PayMethod;
import com.lxt.pojo.BO.ShopCartBO;
import com.lxt.pojo.BO.SubmitOrderBO;
import com.lxt.pojo.OrderStatus;
import com.lxt.pojo.VO.MerchantOrdersVO;
import com.lxt.pojo.VO.OrderVO;
import com.lxt.service.OrderService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

@Api(value = "地址相关", tags = {"订单相关的api接口"})
@RestController
@RequestMapping("orders")
public class OrdersController extends BaseController {


    @Autowired
    private OrderService orderService;

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private RedisOperator redisOperator;

    @ApiOperation(value = "用户下单", notes = "用户下单", httpMethod = "POST")
    @PostMapping("/create")
    public HttpResult commentLevel(@RequestBody SubmitOrderBO submitOrderBO,
                                   HttpServletRequest request, HttpServletResponse response) {

        if (!submitOrderBO.getPayMethod().equals(PayMethod.WEIXIN.type) &&
                !submitOrderBO.getPayMethod().equals(PayMethod.ALIPAY.type)) {
            return HttpResult.errorMsg("支付方式不支持！");
        }

        System.out.println(submitOrderBO.toString());

        String shopCartJson = redisOperator.get(FOODIE_SHOP_CART + ":" + submitOrderBO.getUserId());
        if (StringUtils.isBlank(shopCartJson)) {
            return HttpResult.errorMsg("购物车数据不正确!");
        }
        List<ShopCartBO> shopCartList = JsonUtils.jsonToList(shopCartJson, ShopCartBO.class);

        //1.创建订单
        OrderVO orderVO = orderService.createOrder(shopCartList, submitOrderBO);
        String orderId = orderVO.getOrderId();

        //2.创建订单以后，移除购物车中已结算(已提交)的商品
        /**
         * 1001
         * 2002 -> 用户购买
         * 3003 -> 用户购买
         * 4004
         */
        //清理覆盖现有的redis中的购物车数据
        shopCartList.removeAll(orderVO.getToBeRemoveShopCartList());
        redisOperator.set(FOODIE_SHOP_CART + ":" + submitOrderBO.getUserId(), JsonUtils.objectToJson(shopCartList));
        // 整合redis之后，完善购物车中已结算商品清除，并且同步到前端cookie
        CookieUtils.setCookie(request, response, FOODIE_SHOP_CART, "", true);


        //3.向支付中心发送当前订单，用于保存支付中新的订单数据
        MerchantOrdersVO merchantOrdersVO = orderVO.getMerchantOrdersVO();
        merchantOrdersVO.setReturnUrl(payReturnUrl);
        //为了方便测试购买，所以所有的支付金额都统一改为一分钱
        merchantOrdersVO.setAmount(1);

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.add("imoocUserId", "imooc ");
        headers.add("password", "imooc ");

        HttpEntity<MerchantOrdersVO> entity = new HttpEntity<>(merchantOrdersVO, headers);

        ResponseEntity<HttpResult> responseEntity =
                restTemplate.postForEntity(paymentUrl, entity, HttpResult.class);

        HttpResult paymentResult = responseEntity.getBody();

        if (paymentResult.getStatus() != 200) {
            return HttpResult.errorMsg("支付中心创建失败，请联系管理员");
        }

        return HttpResult.ok(orderId);
    }


    @ApiOperation(value = "回调接口", notes = "回调接口", httpMethod = "POST")
    @PostMapping("/notifyMerchantOrderPaid")
    public Integer notifyMerchantOrderPaid(String merchantOrderId) {
        orderService.updateOrderStatus(merchantOrderId, OrderStatusEnum.WAIT_DELIVER.type);
        return HttpStatus.OK.value();
    }

    @ApiOperation(value = "回调接口", notes = "回调接口", httpMethod = "POST")
    @PostMapping("/getPaidOrderInfo")
    public HttpResult getPaidOrderInfo(String orderId) {
        OrderStatus orderStatus = orderService.queryOrderStatusInfo(orderId);
        return HttpResult.ok(orderStatus);
    }
}
